﻿using FangPage.Admin.Model;
using FangPage.Common;
using FangPage.Core;
using FangPage.Data;
using FangPage.User;
using FangPage.User.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FangPage.Admin.Controller
{
    public class role_menus : UserController
    {
        protected RoleInfo roleinfo = new RoleInfo();

        protected List<MenuInfo> menulist = new List<MenuInfo>();

        public override void Controller()
        {
            string roleid = FPRequest.GetString("roleid");

            roleinfo = DbHelper.ExcuteModel<RoleInfo>(roleid);

            if (roleinfo.id.IsNullOrEmpty())
            {
                FPResponse.WriteErr("对不起，该角色已被删除或不存在！");
                return;
            }

            if (ispost)
            {
                string menus = FPRequest.GetString("menus");

                SqlParam[] update_sql =
                {
                    DbHelper.MakeSet("menus",menus),
                    DbHelper.MakeAndWhere("id",roleinfo.id)
                };

                DbHelper.ExcuteUpdate<RoleInfo>(update_sql);

                FPResponse.WriteSuccess("保存成功。");
                return;
            }

            SqlParam sqlparam = DbHelper.MakeOrderBy("display", OrderBy.ASC);

            menulist = DbHelper.ExcuteList<MenuInfo>(sqlparam);

            List<FPObject> data = GetMenuChildren("");

            FPResponse.WriteData(data);
        }

        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<FPObject> GetMenuChildren(string parentid)
        {
            List<FPObject> menus_data = new List<FPObject>();

            List<MenuInfo> children = menulist.Where(item => item.parentid == parentid).ToList();

            foreach (var item in children)
            {
                FPObject obj = new FPObject();

                obj["title"] = item.name;
                obj["id"] = item.id;
                obj["field"] = item.display;
                obj["spread"] = true;

                List<FPObject> menus_children = GetMenuChildren(item.id);

                if (menus_children.Count == 0)
                {
                    if (FPArray.InArray(item.id, roleinfo.menus) >= 0)
                    {
                        obj["checked"] = true;
                    }
                }

                obj["children"] = menus_children;

                menus_data.Add(obj);
            }

            return menus_data;
        }
    }
}
